#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <malloc.h>
#include <unistd.h>

MyFILE* my_fopen(const char *path, const char *mode)
{

    umask(0);
    int fd = -1;
    if(strcmp(mode,"r")==0)
        fd = open(path,O_RDONLY);
    else if(strcmp(mode,"w")==0)
        fd = open(path,O_WRONLY|O_TRUNC|O_CREAT,0666);
    else if(strcmp(mode,"a")==0)
        fd = open(path,O_WRONLY|O_APPEND|O_CREAT,0666);
    else    
        return NULL;

    MyFILE* fp = (MyFILE*)malloc(sizeof(MyFILE));
    if(fp==NULL)    return NULL;
    fp->fileno = fd;
    fp->pos = 0;
    fp->cap = MAXCAP;
    fp->flushmode = LINE_FLUSH;

    return fp;
}

void my_fflush(MyFILE* fp)
{
    if(fp->pos==0)  return;
    write(fp->fileno,fp->buffer,fp->pos);
    fp->pos = 0;

}

size_t my_fwrite(const void *ptr, size_t size,MyFILE* fp)
{
    memcpy(fp->buffer,ptr,size);
    fp->pos += size;//每次写入增加size长度
    
    if((fp->flushmode & LINE_FLUSH) && fp->buffer[fp->pos-1] == '\n')
        my_fflush(fp);
    else if((fp->flushmode&LINE_FLUSH) && fp->pos == fp->cap)
        my_fflush(fp);

    return size;

}

void my_fclose(MyFILE *fp)
{
    close(fp->fileno);
    free(fp); 
}
